// components/blog-ctrl/blog-ctrl.js
import nowTime from '../../utils/nowTime'
let userInfo = {}
const db = wx.cloud.database()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    blogId: String,
    blog: Object
  },
  externalClasses: ['iconfont', 'icon-chat', 'icon-share'],

  /**
   * 组件的初始数据
   */
  data: {
    loginShow: false,
    commengModal: false,
    content: ''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onComment () {
      // 判断用户是否授权
      wx.requestSubscribeMessage({
        tmplIds: ['JkrMpvhIrmfRU3BdLeWlzuGka-9BMJn-_6v52-94vY4'],
        success: (res) => {
          wx.getSetting({
            success: (res) => {
              if (res.authSetting['scope.userInfo']) {
                wx.getUserInfo({
                  success: (result) => {
                    userInfo = result.userInfo
                    this.setData({ commengModal: true })
                  }
                });
              } else {
                this.setData({ loginShow: true })
              }
            }
          })
        }
      })
    },

    onLoginsuccess (event) {
      userInfo = event.detail
      this.setData({ loginShow: false }, () => {
        this.setData({ commengModal: true })
      })
    },

    onLoginfail () {
      wx.showModal({
        title: '授权后才能进行评论...'
      })
    },
    onInput (event) {
      this.setData({ content: event.detail.value })
    },
    onSend (event) {
      // 发送评论
      let formId = event.detail.formId
      let content = this.data.content
      if (content.trim() == '') {
        wx.showToast({
          title: '评论内容不能为空',
          icon: 'none'
        });
        return
      }
      wx.showLoading({
        title: '评价中',
        mask: true
      })
      let createTime = db.serverDate()
      console.log(createTime)
      db.collection('blog-comment').add({
        data: {
          content,
          createTime: createTime,
          blogId: this.properties.blogId,
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl
        }
      }).then(res => {
        // 模板消息推送
        wx.cloud.callFunction({
          name: 'sendMessage',
          data: {
            content,
            formId,
            fatherContent: this.properties.blog.content,
            createTime: nowTime(),
            nickName: userInfo.nickName,
            blogId: this.properties.blogId
          }
        }).then(res => {
        })
        // 模板消息推送
        wx.hideLoading()
        wx.showToast({ title: '评论成功' })
        this.setData({ commengModal: false, content: '' })
        // 刷新父元素
        this.triggerEvent('refreshCommentList')
      })
    }
  }
})
